import { defineStore } from "pinia";
import { ref, computed } from "vue";

interface UserInfo {
  userId?: string;
  username?: string;
  phone?: string;
  avatar?: string;
  gender?: string;
  birthday?: string;
  idCard?: string;
  loginTime?: string;
  expireTime?: string;
  ipaddr?: string;
  token?: string;
}

interface UserData {
  permissions: string[];
  roles: string[];
  staff: any;
  user: UserInfo;
}

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref<string>("");
    const userInfo = ref<UserInfo>({
      userId: "",
      username: "",
      phone: "",
      avatar: "",
      gender: "",
      birthday: "",
      idCard: "",
    });

    const userData = ref<UserData>({
      permissions: [],
      roles: [],
      staff: null,
      user: {
        userId: "",
        username: "",
        avatar: "",
      },
    });

    // 计算用户是否已登录
    const isLogin = computed(() => {
      return !!token.value && !!userInfo.value.userId;
    });

    // 设置用户信息
    const setUserInfo = (info: Partial<UserInfo>) => {
      userInfo.value = { ...userInfo.value, ...info };
    };

    // 设置用户完整数据（包含权限、角色等）
    const setUserData = (data: UserData) => {
      userData.value = data;
      // 同时更新userInfo中的用户基本信息
      if (data.user) {
        userInfo.value = { ...userInfo.value, ...data.user };
      }
    };

    // 设置token
    const setToken = (newToken: string) => {
      token.value = newToken;
    };

    // 登录
    const login = (loginInfo: { userInfo: UserInfo }) => {
      userInfo.value = loginInfo.userInfo;
    };

    // 清除用户信息并退出登录
    const logout = () => {
      token.value = "";
      userInfo.value = {
        userId: "",
        username: "",
        phone: "",
        avatar: "",
        gender: "",
        birthday: "",
        idCard: "",
      };
      userData.value = {
        permissions: [],
        roles: [],
        staff: null,
        user: {
          userId: "",
          username: "",
          avatar: "",
        },
      };
      uni.removeStorageSync("user");
      console.log("用户已退出登录");
    };

    // 更新头像
    const updateAvatar = (avatar: string) => {
      userInfo.value.avatar = avatar;
    };

    // 获取登录状态的方法
    const getIsLogin = () => {
      console.log("获取登录状态:", isLogin.value);
      console.log("token:", token.value);
      console.log("userInfo:", userInfo.value);
      // 直接返回计算属性的值
      console.log(
        "!!token.value && !!userInfo.value.userId",
        !!token.value && !!userInfo.value.userId
      );
      return !!token.value && !!userInfo.value.userId;
    };

    return {
      token,
      userInfo,
      userData,
      isLogin,
      getIsLogin,
      setUserInfo,
      setUserData,
      setToken,
      login,
      logout,
      updateAvatar,
    };
  },
  {
    persist: true,
  }
);
